const { orderDetail, orderPay, receipt, cancelOrder } = require('../../api/order')
const { API_OK } = require('../../utils/setting')
const { orderStatus } = require('../../utils/util')

Page({
  data: {
    orderType: null, // 订单类型： 1.商品订单 2.课程订单
    orderStatus: null,
    orderNumber: '', // 订单编号
    addressInfo: null, // 收货地址
    orderContent: [], // 订单内容
    expressCompany: '', // 物流公司
    expressNumber: '', // 物流单号
    expressPrice: 0, // 快递费
    payPrice: 0, // 实付款
    createTime: '', // 创建时间
    payTime: '', // 付款时间
    sendTime: '' // 发货时间
  },
  pageData: {
    orderId: null,
  },
  onLoad: function (options) {
    this.pageData.orderId = options.id
    this.getOrderInfo()
  },
  /**
   * 复制文字
   */
  copy({currentTarget}) {
    wx.setClipboardData({
      data: currentTarget.dataset.text,
      success: (result)=>{
        console.log(result)
        wx.showToast({ title: '复制成功', icon: 'none', duration: 1500 })
      }
    })
  },
  /**
   * 跳转至评价页面
   */
  goEvaluate() {
    wx.navigateTo({ url: `/pages/evaluate/evaluate?id=${this.pageData.orderId}` })
  },
  /**
   * 获取订单信息
   */
  async getOrderInfo() {
    wx.showLoading({ title: '拼命加载中', mask: true })
    try {
      const res = await orderDetail({
        data: { order_id: this.pageData.orderId },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        this.setData({
          orderType: res.data.type,
          orderNumber: res.data.order_no,
          addressInfo: res.data.address,
          expressCompany: res.data.express_company,
          expressNumber: res.data.express_no,
          expressPrice: res.data.express_price,
          credit: res.data.score_num * 1,
          payPrice: res.data.pay_price,
          createTime: res.data.create_time,
          payTime: res.data.pay_time_text,
          sendTime: res.data.delivery_time_text,
          orderStatus: orderStatus(
            res.data.order_status.value,
            res.data.pay_status.value,
            res.data.delivery_status.value,
            res.data.receipt_status.value,
            res.data.is_comment
          ),
          orderContent: res.data.goods.map(item => {
            return {
              id: item.goods_id,
              image: item.image.file_path,
              name: item.goods_name,
              specification: item.goods_attr,
              price: item.goods_price,
              number: item.total_num
            }
          })
        })
      } else {
        wx.showToast({ title: res.msg, duration: 1500, icon: 'none' })
      }
    } catch(err) {
      console.warn(err)
      wx.hideLoading()
    }
  },
  /**
   * 取消订单确认提示
   */
  confirmCancel() {
    return new Promise((resolve, reject) => {
      wx.showModal({
        title: '提示',
        content: '确定要取消订单吗？',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#999',
        confirmText: '确定',
        confirmColor: '#121314',
        success: (result) => {
          if(result.confirm){
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: ()=>{
          resolve(false)
        }
      })
    })
  },
  /**
   * 取消订单
   */
  async cancel() {
    const confirm = await this.confirmCancel()
    if (!confirm) return
    try {
      wx.showLoading({ title: '正在取消订单', mask: true })
      const res = await cancelOrder({
        data: { order_id: this.pageData.orderId },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        wx.showToast({ title: '订单取消成功', icon: 'success', mask: true, duration: 1500 })
        setTimeout(() => {
          wx.navigateBack({ delta: 1 })
        }, 1500)
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 付款
   */
  async payForOrder() {
    try {
      wx.showLoading({ title: '正在处理', mask: true })
      const res = await orderPay({
        data: { order_id: this.pageData.orderId },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        this.pay(res.data)
      }
    } catch(err) {
      console.log(err)
    }
  },
  /**
   * 付款
   */
  pay(config) {
    wx.requestPayment({
      timeStamp: config.timeStamp,
      nonceStr: config.nonceStr,
      package: `prepay_id=${config.prepay_id}`,
      signType: 'MD5',
      paySign: config.paySign,
      success: (result)=>{
        // console.log(result)
        if (result.errMsg === 'requestPayment:ok') {
          // wx.switchTab({ url: '/pages/home/home' })
          wx.showToast({ title: '付款成功', success: true, mask: true, duration: 1500 })
          setTimeout(this.getOrderInfo, 1500)
        }
      },
      fail: (err)=>{
        console.warn(err)
        wx.showToast({ title: '支付失败', icon: 'none', duration: 1500, mask: true })
      },
      complate: () => {
        this.pageData.submit = false
      }
    })
  },
  /**
   * 确认收货
   */
  async confirmReceipt() {
    try {
      wx.showLoading({ title: '正在处理', mask: true })
      const res = await receipt({
        data: { order_id: this.pageData.orderId },
        callback: wx.hideLoading
      })
      console.log(res)
      if (res.code === API_OK) {
        wx.showToast({ title: '收货成功', icon: 'success', duration: 1500 })
        setTimeout(() => {
          wx.navigateBack({ delta: 1 })
        }, 1500)
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 1500,
          mask: true
        })
      }
    } catch(err) {
      console.warn(err)
      wx.hideLoading()
    }
  }
})
